package com.dongshan.myregistry.health;

import com.dongshan.myregistry.beans.InstanceMeta;
import com.dongshan.myregistry.service.RegisterService;
import com.dongshan.myregistry.service.impl.MyRegistryService;
import com.google.common.base.Throwables;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.*;



public class MyCheckHealth implements CheckHealth{

    private static final Logger log = LoggerFactory.getLogger(MyCheckHealth.class);
   public static final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    public static final long timeout = 30 * 1000;

    @Resource
    private final RegisterService registerService;


    public MyCheckHealth(RegisterService registerService){
        this.registerService = registerService;
    }

    @Override
    public void start() {
        // 定义定时任务，每隔10s检查一次心跳
        executor.scheduleWithFixedDelay(()->{
            // 1.检查所有服务列表
            try {
                log.debug("===> check health server:{}",MyRegistryService.TIMESTAMPS);
                for (String serverAndInstance : MyRegistryService.TIMESTAMPS.keySet()) {
                    long diffTime = System.currentTimeMillis() - MyRegistryService.TIMESTAMPS.get(serverAndInstance);
                    log.debug("===> check health serverandInsatance:{},diffTime:{}",serverAndInstance,diffTime);
                    // 1.1.如果某个服务超时，注销该服务
                    if (System.currentTimeMillis() - MyRegistryService.TIMESTAMPS.get(serverAndInstance) > timeout) {
                        int index = serverAndInstance.indexOf("@");
                        String server = serverAndInstance.substring(0,index);
                        String url = serverAndInstance.substring(index + 1);
                        InstanceMeta instanceMeta = InstanceMeta.fromUrl(url);
                        log.debug("===> unregister server:{},instanceMeta:{}",server,instanceMeta);
                        registerService.unregister(server, instanceMeta);
                        MyRegistryService.TIMESTAMPS.remove(serverAndInstance);
                    }
                }
            }catch (Exception e){
                log.error(Throwables.getStackTraceAsString(e));
            }
        },10,10,TimeUnit.SECONDS);
    }

    @Override
    public void stop() {
        executor.shutdown();
    }
}
